package com.hzit.gateway.config;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.QueryRoutePredicateFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 类名：
 * 作者：WF
 * 功能：自定义年龄断言工厂类
 * 定类断言工厂类注意：
 * ① 命名：断言名 + RoutePredicateFactory
 * ② 必须继承AbstractRoutePredicateFactory<类名.Config>
 * ③ 定义内部静态类Config，主要对参数进行说明
 * ④ 定义shortcutFieldOrder（）方法：主要对Config类中的参数顺序进行说明。
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
	public AgeRoutePredicateFactory() {
		super(AgeRoutePredicateFactory.Config.class);
	}

	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge","maxAge");
	}
	//1. 进行断言匹配
	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return new Predicate<ServerWebExchange>() {
			@Override
			public boolean test(ServerWebExchange exchange) {
				//1. 得到age参数
				String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
				//2. 如果有值就转换为int
				if(StrUtil.isNotBlank(ageStr)){
					int age = Integer.parseInt(ageStr);
					if (age > config.getMinAge() && age < config.getMaxAge()) {
						return true;
					}
				}
				return false;
			}
		};

	}

	@Data
	public static class Config{
		private int minAge;
		private int maxAge;
	}
}
